package boun.swe.bob.service;

import boun.swe.bob.entities.Friend;
import boun.swe.bob.entities.FriendsPK;
import boun.swe.bob.entities.User;
import boun.swe.bob.entities.UserInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * This controller is used for my info page actions
 */
public class MyInfoController extends BaseController {

    /**
     * Shows the page
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return page
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView showPage(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();
        String wantedUserId = httpServletRequest.getParameter("wantedUserId");

        User wantedUser = null;

        if(null == wantedUserId) {
            wantedUser=userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId());
            myModel.put("user", wantedUser);
            myModel.put("himself",  true  );
            myModel.put("wantedUserId",getLoggedInUser(httpServletRequest).getUserId());
        } else {
            wantedUser=userDao.findByPrimaryKey(Integer.parseInt(wantedUserId));
            myModel.put("user", wantedUser);
            myModel.put("himself",  false  );
            myModel.put("wantedUserId",httpServletRequest.getParameter("wantedUserId"));
        }

        boolean isHeFriend = isHeFriend(getLoggedInUser(httpServletRequest), wantedUser);
        boolean friendshipApprovalWaiting = false;
        if(isHeFriend) {
            FriendsPK friendPK = new FriendsPK();
            friendPK.setUser1Id(getLoggedInUser(httpServletRequest).getUserId());
            friendPK.setUser2Id(Integer.parseInt(wantedUserId));
            Friend friend = friendDao.findByPrimaryKey(friendPK);
            if(null != friend)
                friendshipApprovalWaiting = friend.getApproved() == 0 ? true : false;
        }
        myModel.put("loggedInUser", getLoggedInUser(httpServletRequest));
        myModel.put("isHeFriend", isHeFriend);
        myModel.put("friendshipApprovalWaiting", friendshipApprovalWaiting);

        return new ModelAndView("myInfo", "model", myModel);
    }


    /**
     * Handles HTTP POST action
     *
     * @param httpServletRequest http request
     * @param httpServletResponse http response
     * @return the result message
     */
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView handlePost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        Map<String, Object> myModel = Maps.newHashMap();

        String username = httpServletRequest.getParameter("username");
        String name= httpServletRequest.getParameter("name");
        String surname= httpServletRequest.getParameter("surname");
        String password = httpServletRequest.getParameter("password");
        String repassword = httpServletRequest.getParameter("repassword");
        String birthday = httpServletRequest.getParameter("birthday");
        String gsm = httpServletRequest.getParameter("gsm");
        String hobbies = httpServletRequest.getParameter("hobbies");
        String interests = httpServletRequest.getParameter("interests");
        String conferences = httpServletRequest.getParameter("conferences");


        UserInfo userInfo = new UserInfo();
        try {
            userInfo.setBirthday(new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        userInfo.setUserId(getLoggedInUser(httpServletRequest).getUserId());
        userInfo.setGsm(gsm);
        userInfo.setHobbies(hobbies);
        userInfo.setInterests(interests);
        userInfo.setConferences(conferences);
        userInfoDao.saveOrUpdate(userInfo);

        if(!Strings.isNullOrEmpty(name))
        {
            getLoggedInUser(httpServletRequest).setName(name);
            userDao.update(getLoggedInUser(httpServletRequest));
        }

          if(!Strings.isNullOrEmpty(surname))
        {
            getLoggedInUser(httpServletRequest).setSurname(surname);
            userDao.update(getLoggedInUser(httpServletRequest));
        }

        if(!Strings.isNullOrEmpty(username)) {
            getLoggedInUser(httpServletRequest).setUsername(username);
            userDao.update(getLoggedInUser(httpServletRequest));
        }
        if(!Strings.isNullOrEmpty(password)) {
            if(password.equals(repassword)) {
                getLoggedInUser(httpServletRequest).setPassword(userDao.createMd5Password(password));
                userDao.update(getLoggedInUser(httpServletRequest));
            }
        }
        String wantedUserId = httpServletRequest.getParameter("wantedUserId");

        User wantedUser = null;

        if(null == wantedUserId) {
            wantedUser=userDao.findByPrimaryKey(getLoggedInUser(httpServletRequest).getUserId());
            myModel.put("user", wantedUser);
            myModel.put("himself",  true  );
            myModel.put("wantedUserId",getLoggedInUser(httpServletRequest).getUserId());
        } else {
            wantedUser=userDao.findByPrimaryKey(Integer.parseInt(wantedUserId));
            myModel.put("user", wantedUser);
            myModel.put("himself",  false  );
            myModel.put("wantedUserId",httpServletRequest.getParameter("wantedUserId"));
        }

        boolean isHeFriend = isHeFriend(getLoggedInUser(httpServletRequest), wantedUser);
        boolean friendshipApprovalWaiting = false;
        if(isHeFriend) {
            FriendsPK friendPK = new FriendsPK();
            friendPK.setUser1Id(getLoggedInUser(httpServletRequest).getUserId());
            friendPK.setUser2Id(Integer.parseInt(wantedUserId));
            Friend friend = friendDao.findByPrimaryKey(friendPK);
            if(null != friend)
                friendshipApprovalWaiting = friend.getApproved() == 0 ? true : false;
        }
        myModel.put("loggedInUser", getLoggedInUser(httpServletRequest));
        myModel.put("isHeFriend", isHeFriend);
        myModel.put("friendshipApprovalWaiting", friendshipApprovalWaiting);

        return new ModelAndView("myInfo", "model", myModel);
    }
    
    private boolean isHeFriend(User loggedInUser, User wantedUser){
        for (Friend friend : loggedInUser.getFriends()) {
            if(wantedUser.getUserId().intValue() == friend.getUser2Id().intValue()) {
                return true;
            }
        }
        return false;
    }

}
